#include "votesys.h"
#include<stdio.h>
#include<string.h>

static void
unmarshal_results(countList *l, NetMessage msg)
{
  int i, j, count; 
  char name[MAXSTLEN]; 
  FILE *f;

  if( l == NULL )
    return;
 
  f = fopen("tmp", "w");
  fprintf(f, msg.data);
  fclose(f);
 
  f = fopen("tmp","r");
  for(i=(msg.length), j=0; i>0; i--, j++)
  {
     fscanf(f, "%s %d", name, &count);
     strcpy((l->array[j]).name, name);
     (l->array[j]).count = count;
     (l->num)++;
  }
  fclose(f); 
}


int 
main(int argc, char** argv)
{
   CLIENT *cl;
   countList list;
   int i;
   int status;
   NetMessage msg; 
   struct timeval tv; 

   list.num = 0;

   cl = clnt_create("localhost", VOTESYS, VOTEVERS, "tcp");

   if( cl == NULL )
   {
     clnt_pcreateerror("Server");
     return 1;
   }

   /*destory previous auth*/
   auth_destroy(cl->cl_auth);

   cl->cl_auth = authsys_create_default();

   //set timeout
   tv.tv_sec = 1;
   tv.tv_usec = 0;
   clnt_control(cl, CLSET_TIMEOUT, &tv);

   if( (status = results_1(NULL, &msg, cl)) != RPC_SUCCESS )
   {
      //clnt_perror(cl, "Server"); 
      fprintf(stderr, "Get Results Unsuccessful!\n");
      return -1;
   }

   unmarshal_results(&list, msg);

   for(i=0; i<list.num; i++)
   {
     printf("%s - %d vote\n", list.array[i].name, list.array[i].count);
   }
   return 0; 
}
